package cn.fzkj.config;

import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.function.Predicate;

/**
 * gateway 的配置类
 * 三大核心概念：
 *  - 路由（route）
 *  - 断言（predicates）
 *  - 过滤器（filter）
 */
@Configuration
public class GatewayConfiguration {
    @Bean
    public RouteLocator myRoutes(RouteLocatorBuilder builder){
        System.out.println("======== gateway 网管 =========");
//        return builder.routes()
//                .route("payment-route", p -> p.path("/payment/getPaymentById/**")
//                .uri("http://localhost:8001"))
//
//                .route("baidu-route", p -> p.path("/tobaidu")
//                .uri("http://www.baidu.com/"))
//                .build();

        /**
         * 配置uri为微服务实例名需要在yaml中配置
         * gateway:
         *       discovery:
         *         locator:
         *           enabled: true
         */
        return builder.routes()
                .route("payment-route", p -> p.path("/payment/getPaymentById/**")
                        .uri("lb://cloud-payment-service")
                .filter(new GatewayFilter() {
                    @Override
                    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
                        return null;
                    }
                })
                .predicate(new Predicate<ServerWebExchange>() {
                    @Override
                    public boolean test(ServerWebExchange serverWebExchange) {
                        String name = serverWebExchange.getRequest().getQueryParams().getFirst("name");
                        // do something
                        return false;
                    }
                }))
                .build();
    }
}
